package com.hosp.web;

import java.io.IOException;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hosp.bean.Sysuser;

/**
 * 登录认证过滤器
 *
 * @author ztranscript 2021/9/11 12:01
 **/
@WebFilter(urlPatterns = {"*.html"}, filterName = "loginFilter")
public class LoginFilter implements Filter {
    private static final Set<String> ALLOWED_PATHS
            = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("/pages/login.html")));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getRequestURI()
                .substring(request.getContextPath().length())
                .replaceAll("[/]+$", "");
        System.out.println(path + "...");
        boolean allowedPath = ALLOWED_PATHS.contains(path);
        if (allowedPath) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

        // 获取当前登录用户对象
        Sysuser userInfo = (Sysuser) request.getSession().getAttribute("userInfo");
        if (Objects.isNull(userInfo)) {
            // 尚未登录,前往登录页面
            response.sendRedirect("/pages/login.html");
        }
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
